<template>
  <div class="basic-info p-6">
    <div class="mb-6">
      <h2 class="text-xl font-semibold text-gray-800">基础信息</h2>
      <p class="text-gray-500 text-sm mt-1">管理您的账号基本信息</p>
    </div>

    <el-form 
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
      class="max-w-2xl"
    >
      <!-- Avatar Upload -->
      <el-form-item label="头像" prop="avatar">
        <div class="flex items-start gap-6">
          <div class="relative group">
            <img 
              :src="form.avatar || 'https://picsum.photos/seed/user/100/100'" 
              alt="Avatar Preview"
              class="w-24 h-24 rounded-lg object-cover border-2 border-gray-200"
              @error="handleImageError"
            />
            <div class="absolute inset-0 bg-black bg-opacity-50 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-icon class="text-white text-xl"><Camera /></el-icon>
              </el-upload>
            </div>
          </div>
          <div class="text-sm text-gray-500 mt-2">
            <p>支持 jpg、png 格式大小 5MB 以内的图片</p>
            <p>建议尺寸为 200x200 像素</p>
          </div>
        </div>
      </el-form-item>

      <!-- Basic Info Form -->
      <div class="grid grid-cols-2 gap-6">
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="form.username"
            placeholder="请输入用户名"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input 
            v-model="form.nickname"
            placeholder="请输入昵称"
          >
            <template #prefix>
              <el-icon><UserFilled /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="form.email"
            placeholder="请输入邮箱"
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="form.phone"
            placeholder="请输入手机号"
          >
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </div>

      <el-form-item label="个人简介" prop="bio">
        <el-input 
          v-model="form.bio"
          type="textarea"
          :rows="4"
          placeholder="请输入个人简介"
          resize="none"
        />
      </el-form-item>

      <!-- Gender Selection -->
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender" class="flex gap-6">
          <el-radio-button label="male">
            <el-icon><Male /></el-icon> 男
          </el-radio-button>
          <el-radio-button label="female">
            <el-icon><Female /></el-icon> 女
          </el-radio-button>
          <el-radio-button label="other">
            <el-icon><User /></el-icon> 其他
          </el-radio-button>
        </el-radio-group>
      </el-form-item>

      <!-- Birthday -->
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          v-model="form.birthday"
          type="date"
          placeholder="选择生日"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          class="w-full"
        />
      </el-form-item>

      <!-- Location -->
      <el-form-item label="所在地" prop="location">
        <el-cascader
          v-model="form.location"
          :options="locationOptions"
          placeholder="请选择所在地"
          class="w-full"
        />
      </el-form-item>

      <!-- Submit Button -->
      <el-form-item>
        <div class="flex items-center gap-4">
          <el-button type="primary" @click="handleSubmit" :loading="isSubmitting">
            保存修改
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { User, UserFilled, Message, Phone, Camera, Male, Female } from '@element-plus/icons-vue'

const formRef = ref<FormInstance>()
const isSubmitting = ref(false)

const form = ref({
  avatar: '',
  username: '',
  nickname: '',
  email: '',
  phone: '',
  bio: '',
  gender: 'male',
  birthday: '',
  location: []
})

const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// Mock location data
const locationOptions = [
  {
    value: 'beijing',
    label: '北京',
    children: [
      { value: 'chaoyang', label: '朝阳区' },
      { value: 'haidian', label: '海淀区' }
    ]
  },
  {
    value: 'shanghai',
    label: '上海',
    children: [
      { value: 'pudong', label: '浦东新区' },
      { value: 'huangpu', label: '黄浦区' }
    ]
  }
]

// Avatar upload handlers
function handleAvatarSuccess(response: any) {
  form.value.avatar = response.url
  ElMessage.success('头像上传成功')
}

function beforeAvatarUpload(file: File) {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('头像大小不能超过 5MB!')
    return false
  }
  return true
}

// Form submission
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    isSubmitting.value = true
    
    // TODO: Implement API call
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('Form validation failed:', error)
  } finally {
    isSubmitting.value = false
  }
}

function resetForm() {
  if (!formRef.value) return
  formRef.value.resetFields()
}

// 图片加载失败处理
function handleImageError(e: Event) {
  const target = e.target as HTMLImageElement
  if (target) {
    target.src = '/src/assets/images/avatar-placeholder.png'
  }
}
</script>

<style scoped>
.avatar-uploader {
  @apply cursor-pointer;
}

:deep(.el-form-item__label) {
  @apply text-gray-600 font-medium;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  @apply shadow-sm;
}

:deep(.el-input__wrapper:hover),
:deep(.el-textarea__inner:hover) {
  @apply shadow;
}

:deep(.el-radio-button__inner) {
  @apply flex items-center gap-1;
}
</style> 